package ru.niir.goodfil.ui.tasks;

import org.apache.log4j.Logger;
import ru.niir.goodfil.db.*;
import ru.niir.goodfil.db.handlers.Goodfil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.TimerTask;

public class PersonalPricesExpirationTask extends TimerTask
{
    private static final Logger logger = Logger.getLogger(PersonalPricesExpirationTask.class);

    private static final SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");

    private static final String PERSONAL_PRICE_EXPIRATION_WARNING_DAYS = "personal.price.expiration.warning.days";

    private static final String PERSONAL_PRICE_EXPIRATION_WARNING_DAYS_COMMENT = "Количество дней до истечения срока действия персональных цен";

    private static final int PERSONAL_PRICE_EXPIRATION_WARNING_DAYS_DEFAULT = 7;

    @Override
    public void run()
    {
        logger.debug("PersonalPricesExpirationTask call");

        try
        {
            Goodfil gf = GoodfilFactory.getInstance();
            int days = gf.getIntOrCreateIfNotExists(PERSONAL_PRICE_EXPIRATION_WARNING_DAYS, PERSONAL_PRICE_EXPIRATION_WARNING_DAYS_DEFAULT, PERSONAL_PRICE_EXPIRATION_WARNING_DAYS_COMMENT);

            User admin = gf.getAdminUser();

            List<PersonalPrice> personalPrices = gf.getAllPersonalPrices();
            for (PersonalPrice personalPrice : personalPrices)
            {
                long beg = personalPrice.getBegDate() == null ? Long.MIN_VALUE : personalPrice.getBegDate().getTime();
                long end = personalPrice.getBegDate() == null ? Long.MAX_VALUE : personalPrice.getEndDate().getTime();
                long curr = Calendar.getInstance().getTimeInMillis();

                long d = end - curr;
                if (d > 0 && d < 1000 * 60 * 60 * days)
                {
                    Client client = gf.getClientById(personalPrice.getClientId());
                    if (client == null) continue;

                    Good good = gf.getGoodById(personalPrice.getGoodId());
                    if (good == null) continue;

                    String msg = "Персональная цена для клиента \"" + client.getCompanyName() + "\" на товар \"" + good.getName() + "\" истекает в течение ближайших " + days + " дней (дня).";
                    msg += "Срок действия персональной цены: " + (personalPrice.getBegDate() == null ? "?" : sdf.format(personalPrice.getBegDate()));
                    msg += " - ";
                    msg += (personalPrice.getEndDate() == null ? "?" : sdf.format(personalPrice.getEndDate()));
                    msg += ". ";

                    User manager = gf.getUserById(client.getManagerId());

                    gf.sendEmailMsg(manager.getEmail(), msg);
                    gf.sendEmailMsg(admin.getEmail(), msg);
                }
            }
        }
        catch (Exception e)
        {
            logger.error("PersonalPricesExpirationTask error: " + e.getMessage(), e);
        }
    }
}
